package com.dh.leetcode.seven;

import org.junit.Assert;
import org.junit.Test;

/**
 * @ClassName: _704_binary_search
 * @Description: 704. 二分查找
 * 给定一个 n 个元素有序的（升序）整型数组 nums 和一个目标值 target  ，写一个函数搜索 nums 中的 target，如果目标值存在返回下标，否则返回 -1。
 * <p>
 * <p>
 * 示例 1:
 * <p>
 * 输入: nums = [-1,0,3,5,9,12], target = 9
 * 输出: 4
 * 解释: 9 出现在 nums 中并且下标为 4
 * 示例 2:
 * <p>
 * 输入: nums = [-1,0,3,5,9,12], target = 2
 * 输出: -1
 * 解释: 2 不存在 nums 中因此返回 -1
 * <p>
 * https://leetcode-cn.com/problems/binary-search/
 * @Author: shouzimu
 * @Date: 2021/2/5 11:29
 */
public class _704_binary_search {

    public int search(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }

    @Test
    public void searchTest() {
        Assert.assertEquals(-1, search(new int[]{-1, 0, 3, 5, 9, 12}, 13));
        Assert.assertEquals(4, search(new int[]{-1, 0, 3, 5, 9, 12}, 9));
        Assert.assertEquals(-1, search(new int[]{-1, 0, 3, 5, 9, 12}, 2));
        Assert.assertEquals(0, search(new int[]{1}, 1));
    }
}
